package keeper.util;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import keeper.event.Event;
import keeper.event.EventListener;
/**
 * 
 * @author hliang@126.com
 *
 */
public class NameRegister {

	private static String EVENT_PREFIX = "event_";
	private static String EVENT_COUNT_PREFIX = "event_count_";
	private static NameRegister register;
	private Map eventMap = Collections.synchronizedMap(new HashMap());
	
	private NameRegister(){}
	
	public static NameRegister getInstance() {
		if(register == null) {
			register = new NameRegister();
		}
		return register;
	}
	
	public synchronized Event getEvent(String eventName,boolean isControl) throws RegistException{
		if(eventName == null) {
			throw new RegistException(" event name null ");
		} else {
			Integer count = (Integer)eventMap.get(EVENT_COUNT_PREFIX+eventName.trim());
			if(count == null) {
				count = 0;
				eventMap.put(EVENT_COUNT_PREFIX+eventName.trim(), count);
			}
			Object obj = eventMap.remove(EVENT_PREFIX+eventName.trim()+count.intValue());
			if(isControl) {
				count++;
				if(count >= 10000000) {
					count = 0;
				}
				eventMap.put(EVENT_COUNT_PREFIX+eventName.trim(),count);
			}
			return (Event)obj;
		}
	}
	
	public Event getEvent(String eventName) throws RegistException {
		if(eventName == null) {
			throw new RegistException(" event name null ");
		} else {
			Integer count = (Integer)eventMap.get(EVENT_COUNT_PREFIX+eventName.trim());
			if(count == null) {
				count = 0;
				eventMap.put(EVENT_COUNT_PREFIX+eventName.trim(),count);
			}
			Object obj = eventMap.get(EVENT_PREFIX+eventName.trim()+count);
			return (Event)obj;
		}
	}
	
	public void registeEvent(String eventName,Event eventType) throws RegistException {
		if(eventName == null) {
			throw new RegistException(" registe event name null ");
		} else if(eventType == null){
			throw new RegistException(" registe event type null ");
		} else {
			Integer count = (Integer)eventMap.get(EVENT_COUNT_PREFIX+eventName.trim());
			if(count == null) {
				count = 0;
				eventMap.put(EVENT_COUNT_PREFIX+eventName.trim(),count);
			}
			eventMap.put(EVENT_PREFIX+eventName.trim()+count,eventType);
		}
	}
}
